package com.zcx.merchantorder.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.zcx.merchantorder.R;
import com.zcx.merchantorder.base.presenter.BasePresenter;
import com.zcx.merchantorder.base.view.IView;
import com.zcx.merchantorder.entity.MessageEvent;
import com.zcx.merchantorder.util.AppManagerUtil;
import com.zcx.merchantorder.util.EventBusUtils;
import com.zcx.merchantorder.util.Helper;
import com.zcx.merchantorder.util.RxBus;
import com.zcx.merchantorder.util.SharedPreferencesUtil;
import com.zcx.merchantorder.util.ToastUtil;
import com.zcx.merchantorder.util.ToolUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Subscription;
import rx.functions.Action1;
import rx.subscriptions.CompositeSubscription;

public abstract class BaseActivity<V extends IView,P extends BasePresenter<V>> extends AppCompatActivity implements IView{

    protected Intent mIntent;
    private BaseApplication baseApplication;
    private P basePresenter;
    private SharedPreferencesUtil preferencesUtil;
    @BindView(R.id.tv_title)
    private TextView mTvTitle;
    @BindView(R.id.tv_right)
    private TextView mTvRight;
    @BindView(R.id.iv_right)
    private ImageView mRightIcon;
    protected static List<Activity> mActivities = new LinkedList<Activity>();//存储全局的activity
    private static Activity mForegroundActivity;//前台的activity
    public Activity mActivity;
    protected CompositeSubscription mCompositeSubscription;
    /** 是否允许全屏 **/
    private boolean mAllowFullScreen = true;
    /** 是否禁止旋转屏幕 **/
    private boolean isAllowScreenRoate = false;
   /**
   * 获取前台activity
    * @date: 2019/3/3 13:17
    * @author: zcx
    * @return android.app.Activity
    */
    public static Activity getForegroundActivity() {
        return mForegroundActivity;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        AppManagerUtil.getInstance().addActivity(this);
        synchronized (mActivities) {
            mActivities.add(this);
        }
        basePresenter = setPresenter();
        if(Helper.isNotNull(basePresenter)) {
            basePresenter.attachView(getBaseView());
        }
        //注册eventbus
        EventBusUtils.register(this);
        setContentView(getLayoutId());
        //设置是否全屏
        if (mAllowFullScreen) {
            this.getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        //设置是否允许屏幕旋转
        if (!isAllowScreenRoate) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        //绑定初始化ButterKnife
        ButterKnife.bind(this);
        //初始化
        preferencesUtil = new SharedPreferencesUtil(this);
        baseApplication = BaseApplication.getSingleApplication();
    }

    public abstract int getLayoutId();

    protected abstract P setPresenter();

    public P getBasePresenter() {
        return basePresenter;
    }

    protected V getBaseView() {
        return (V) this;
    }

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 所有监听的方法都在该类中实现
     */
    protected abstract void initListener();

    /**
     * 初始化布局
     * @param savedInstanceState
     */
    protected abstract void initLayout(Bundle savedInstanceState);



    /*
    *根据键字符串，存储一个boolean值
     */
    public void putBoolean(String key, boolean value) {
        preferencesUtil.putBoolean(key,value);
    }

    /*
    *根据键字符串，获取一个boolean值
     */
    public  boolean getBoolean(String key, boolean defaultValue) {
        return preferencesUtil.getBoolean(key, defaultValue);
    }

    /*
    *根据键字符串，存储一个浮点型值
     */
    public void putFloat(String key, float value) {
        preferencesUtil.putFloat(key, value);
    }

    /*
    *根据键字符串，获取一个浮点型值
    */
    public float getFloat( String key, float defaultValue) {
        return preferencesUtil.getFloat(key, defaultValue);
    }

    /*
     *根据键字符串，存储一个字符串类型
     */
    public void putString(String key, String value) {
        preferencesUtil.putString(key, value);
    }

    /**
     *获取String类型的值
     */
    public String getString( String key, String defaultValue) {
        return preferencesUtil.getString(key, defaultValue);
    }

    /**
     *设置Long类型的值
     */
    public void putLong(String key, long value) {
        preferencesUtil.putLong(key, value);
    }

    /**
     *获取Long类型的值
     */
    public long getLong(String key, long defaultValue) {
        return preferencesUtil.getLong(key, defaultValue);
    }

    /**
     *设置int类型的值
     */
    public void putInt(String key, int value) {
        preferencesUtil.putInt(key, value);
    }

    /**
     *获取int类型的值
     */
    public int getInt(String key, int defaultValue) {
        return preferencesUtil.getInt(key, defaultValue);
    }

    /*
    *设置右边文字如R.string.XX
     * @date: 2019/3/3 13:12
     * @author: zcx
     * @param text
     * @return void
     */
    public void setRightText(int textId) {
        mTvRight.setText(textId);
    }

    /**
    *设置title文字如：R.string.XX
     * @date: 2019/3/3 13:14
     * @author: zcx
     * @param textId
     * @return void
     */
    public void setTitleText(int textId) {
        mTvTitle.setText(textId);
    }

    /**
    *设置图片资源如：R.mipmap.xxx
     * @date: 2019/3/3 13:15
     * @author: zcx
     * @param pIconRes
     * @return void
     */
    public void setRightIcon(int pIconRes) {
        mRightIcon.setImageResource(pIconRes);
    }

   /**
   *取消订阅
    * @date: 2019/3/3 13:25
    * @author: zcx
    * @param
    * @return void
    */
    protected void unSubscribe() {
        if (mCompositeSubscription != null) {
            mCompositeSubscription.unsubscribe();
            mCompositeSubscription = null;
        }
    }

    /**
    *添加订阅
     * @date: 2019/3/3 13:28
     * @author: zcx
     * @param subscription
     * @return void
     */
    public void addSubscrebe(Subscription subscription) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscription);
    }


   /**
   *管理各组件之间的通信
    * @date: 2019/3/3 13:32
    * @author: zcx
    * @param eventType
    * @param act
    * @return void
    */
    public <U> void addRxBusSubscribe(Class<U> eventType, Action1<U> act) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(RxBus.getDefault().toDefaultObservable(eventType, act));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Helper.isNotNull(basePresenter)) {
            basePresenter.dettachView();
        }
        if(EventBus.getDefault().isRegistered(this)) {
            EventBusUtils.unregister(this);
        }
        unSubscribe();
        synchronized (mActivities) {
            AppManagerUtil.getInstance().killActivity(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mForegroundActivity = this;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mForegroundActivity = null;
    }

   /**
   *接收到分发的事件
    * @date: 2019/3/3 14:07
    * @author: zcx
    * @param event
    * @return void
    */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveEvent(MessageEvent event) {
    }

   /**
   *接受到分发的粘性事件
    * @date: 2019/3/3 14:07
    * @author: zcx
    * @param event
    * @return void
    */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onReceiveStickyEvent(MessageEvent event) {
    }

    /**
    *全局控制是否显示Toast
     * @date: 2019/3/3 14:15
     * @author: zcx
     * @param isShow
     * @return void
     */
    public void isToastShow(boolean isShow)  {
        ToastUtil.isToastShow(isShow);
    }

    /**
    *取消Toast显示
     * @date: 2019/3/3 14:15
     * @author: zcx
     * @param
     * @return void
     */
    public void toastCancel() {
        ToastUtil.toastCancel();
    }

    /**
    *短时间显示Toast
     * @date: 2019/3/3 14:15
     * @author: zcx
     * @param resId 资源ID:getResources().getString(R.string.xxxxxx);
     * @return void
     */
    public void toastShowShort(int resId) {
        ToastUtil.toastShowShort(resId);
    }

    /**
    *长时间显示Toast
     * @date: 2019/3/3 14:15
     * @author: zcx
     * @param resId 资源ID:getResources().getString(R.string.xxxxxx);
     * @return void
     */
    public void toastShowLong(int resId) {
        ToastUtil.toastShowLong(resId);
    }

    /**
    *自定义显示Toast时间
     * @date: 2019/3/3 14:16
     * @author: zcx
     * @param resId 资源ID:getResources().getString(R.string.xxxxxx);
     * @param duration 单位:毫秒
     * @return void
     */
    public void show(int resId, int duration) {
        ToastUtil.show(resId,duration);
    }

    /**
    *自定义Toast的View
     * @date: 2019/3/3 14:17
     * @author: zcx
     * @param resId 资源ID:getResources().getString(R.string.xxxxxx);
     * @param duration 单位:毫秒
     * @param view 显示自己的View
     * @return void
     */
    public void customToastView(int resId, int duration,View view) {
        ToastUtil.customToastView(resId,duration,view);
    }

    /**
    *自定义Toast的位置
     * @date: 2019/3/3 14:18
     * @author: zcx
     * @param resId 资源ID:getResources().getString(R.string.xxxxxx);
     * @param duration 单位:毫秒
     * @param gravity 控制显示的位置如:Gravity.CENTER,Gravity.LEFT等
     * @param xOffset x轴偏移量
     * @param yOffset y轴偏移量
     * @return void
     */
    public void customToastGravity(int resId, int duration,int gravity, int xOffset, int yOffset) {
        ToastUtil.customToastGravity(resId,duration,gravity,xOffset,yOffset);
    }

    /**
    *自定义带图片和文字的Toast，最终的效果就是上面是图片，下面是文字
     * @date: 2019/3/3 14:18
     * @author: zcx
     * @param resId 资源ID:getResources().getString(R.string.xxxxxx);
     * @param iconResId 图片的资源id,如:R.drawable.icon
     * @param duration  单位:毫秒
     * @param gravity 控制显示的位置如:Gravity.CENTER,Gravity.LEFT等
     * @param xOffset x轴偏移量
     * @param yOffset y轴偏移量
     * @return void
     */
    public void showToastWithImageAndText(int resId, int iconResId,int duration,int gravity, int xOffset, int yOffset) {
        ToastUtil.showToastWithImageAndText(resId,iconResId,duration,gravity,xOffset,yOffset);
    }

    /**
    *
     * @date: 2019/3/3 14:20
     * @author: zcx
     * @param resId 资源ID:getResources().getString(R.string.xxxxxx);
     * @param duration 单位:毫秒
     * @param view
     * @param isGravity true,表示后面的三个布局参数生效,false,表示不生效
     * @param gravity 控制显示的位置如:Gravity.CENTER,Gravity.LEFT等
     * @param xOffset x轴偏移量
     * @param yOffset y轴偏移量
     * @param isMargin isMargin true,表示后面的两个参数生效，false,表示不生效
     * @param horizontalMargin 水平
     * @param verticalMargin 垂直
     * @return void
     */
    public void customToastAll(int resId, int duration,View view,boolean isGravity,int gravity, int xOffset, int yOffset,boolean isMargin,float horizontalMargin, float verticalMargin) {
        ToastUtil.customToastAll(resId,duration,view,isGravity,gravity,xOffset,yOffset,isMargin,horizontalMargin,verticalMargin);
    }

    /**
     * 隐藏软件盘
     */
    public void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (getCurrentFocus() != null) {
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 点击软键盘之外的空白处，隐藏软件盘
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (ToolUtil.isShouldHideSoftKeyBoard(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /**
     * 显示软键盘
     */
    public void showInputMethod(){
        if (getCurrentFocus() != null){
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.showSoftInputFromInputMethod(getCurrentFocus().getWindowToken(),0);
        }
    }

    /**
    *打开一个新的activity
     * @date: 2019/3/3 14:41
     * @author: zcx
     * @param pClass
     * @return void
     */
    protected void startActivity(Class<?> pClass) {
        Intent i = new Intent(this, pClass);
        startActivity(i);
    }
    /**
     * 跳转页面
     *
     * @param pClass  跳转的页面
     * @param pBundle 传递过去的参数
     */
    protected void startActivity(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(this, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        startActivity(intent);
        // 动画效果
        // overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
    }
    /**
     * 启动带结果的Activity
     *
     * @param pClass
     * @param pBundle
     * @param requestCode
     */
    protected void startActivityForResult(Class<?> pClass, Bundle pBundle, int requestCode) {
        Intent intent = new Intent(this, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
            startActivityForResult(intent, requestCode);
        } else {
            startActivityForResult(intent, requestCode);
        }
    }

    /**
    *设置是否全屏
     * @date: 2019/3/3 14:50
     * @author: zcx
     * @param allowFullScreen
     * @return void
     */
    public void setAllowFullScreen(boolean allowFullScreen) {
        this.mAllowFullScreen = allowFullScreen;
    }

    /**
    *设置是否允许屏幕旋转
     * @date: 2019/3/3 14:51
     * @author: zcx
     * @param isAllowScreenRoate
     * @return void
     */
    public void setScreenRoate(boolean isAllowScreenRoate) {
        this.isAllowScreenRoate = isAllowScreenRoate;
    }

}
